import numpy as np

def energy_based_spike_removal(original_signal, fs, overlap_ratio=0.5):
    """
    通过窗口能量检测移除信号中的尖峰。
    参数:
      original_signal: 原始的一维音频信号数组
      fs: 采样频率 (Hz)
      overlap_ratio: 相邻窗口的重叠比例（默认值为0.5）
    输出:
      despiked_signal: 已处理高能量窗口的音频信号
      zeroed_time_energy: 因为能量置零的时间（秒）
    """

    # 计算窗口大小 (500 ms)
    windowsize = round(fs / 2)

    # 计算超出完整窗口数的样本数
    trailingsamples = len(original_signal) % windowsize

    # 计算重叠窗口的能量
    overlap_step = round(windowsize * (1 - overlap_ratio))
    num_windows = int(np.ceil((len(original_signal) - trailingsamples) / overlap_step))
    energies = np.zeros(num_windows)

    for i in range(num_windows):
        start_idx = i * overlap_step
        end_idx = start_idx + windowsize
        if end_idx > len(original_signal):
            end_idx = len(original_signal)
        window = original_signal[start_idx:end_idx]
        energies[i] = np.sum(window ** 2)

    # 根据能量的中位数设定阈值
    threshold_energy = 30 * np.median(energies)

    # 初始化置零时间计数器
    zeroed_samples_energy = 0

    # 处理超过能量阈值的窗口，将其值置为0.0001
    for i in range(num_windows):
        if energies[i] > threshold_energy:
            start_idx = i * overlap_step
            end_idx = start_idx + windowsize
            if end_idx > len(original_signal):
                end_idx = len(original_signal)
            zeroed_samples_energy += (end_idx - start_idx)
            original_signal[start_idx:end_idx] = 0.0001

    # 计算置零的时间（秒）
    zeroed_time_energy = zeroed_samples_energy / fs

    # 输出处理后的信号
    despiked_signal = original_signal

    return despiked_signal, zeroed_time_energy
